//
//  PublicExtension.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/4/10.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

func showNETFail(deadline:Double=0.1){
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+deadline) {
        GToast.show(msg: "获取数据失败，检查您的网络，刷新请重试！".localized())
    }
}

func showDataFail(deadline:Double=0.1){
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+deadline) {
        GToast.show(msg: "网络请求不可用".localized())
    }
}

func show_msg(_ msg:String,deadline:Double=0.1){
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+deadline) {
        GToast.show(msg: msg)
    }
}

func showAlert_msg(_ msg:String,deadline:Double=0.36){
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+deadline) {
        let controller =  KlViewController.init(title: nil, massage: msg, buttomTitles: ["确定"], indexBlock: { (index, control) in
            
        }, navBlock: nil)
        let window = NSWindow.init(contentViewController: controller)
        window.makeKeyAndOrderFront(nil)
    }
}

func showNoTitle_msg(_ msg:String,deadline:Double=0.1){
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+deadline) {
        GToast.show(msg: "立即更新")
    }
}


extension String {
    
    func getIntFromString() -> String {
        let scanner = Scanner(string: self)
        scanner.scanUpToCharacters(from: CharacterSet.decimalDigits, into: nil)
        var number :Int = 0
        scanner.scanInt(&number)
        return String(number)
    }
    
    
    /// 整体处理成隔3加空格
    func stringToPhone(c:String=" ",p:Int=3) -> String {
        let text = self
        var newString = ""
        for i in 0 ..< text.count {
            if i%p==0 && i != 0 {
                newString.append(c)
            }
            newString.append(text[i])
        }
        return newString
    }

    /// 实时输入单个字符时，自动添加空格
    func singleToPhone() -> String {
        var newString = self
        if (newString[newString.startIndex] == "0") {
            if  newString.count == 1||newString.count == 5||newString.count == 9 || newString.count == 13 {
                newString.append(" ")
            }
        }else {
            if newString.count == 3||newString.count == 7 || newString.count == 11 {
                newString.append(" ")
            }
        }
        return newString
    }
    
    /// 实时删除单个字符时，自动去掉空格
    @discardableResult
    func removeSingleToLast() -> String {
        var newString = self
        if (newString[newString.endIndex] == " ") {
            newString.remove(at: newString.endIndex)
            newString.removeSingleToLast()
        }
        return newString
    }
    
    func clearId() -> String {
        let text = self
        var newString = text.replacingOccurrences(of: "-", with: "")
        newString = newString.replacingOccurrences(of: " ", with: "")
        return newString
    }
    
    
}


extension NSNumber {
    func toString() -> String? {
        return NumberFormatter().string(from: self)
    }
}


extension String {
    func toNumber() -> NSNumber? {
        let num =  NumberFormatter()
        num.numberStyle = NumberFormatter.Style.decimal
        return num.number(from: self)
    }
    
}

class PE: NSObject {
    class func toString(obj:Any?) -> String? {
        if obj is String {
            return (obj as? String)
        }
        
        if obj is NSNumber {
            return (obj as? NSNumber)?.toString()
        }
        return nil
    }
    
    class func timeNow(dateFormat:String="HH:mm") -> String{
        let d1 = Date()
        /*
        // let timeZone = TimeZone.current
        let timeZone = TimeZone(identifier: "Asia/Shanghai") ?? TimeZone.current
        let interval: Int = timeZone.secondsFromGMT(for: d1)
        let currentDate = d1.addingTimeInterval(Double(interval))
        */
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        dateFormatter.locale = Locale.init(identifier: "zh_CN")
        let dateStr = dateFormatter.string(from: d1)
        return dateStr
    }
}

protocol AnyObj: Any {}
extension AnyObj {
    func toString() -> String? {
        let obj = self
        if obj is String {
            return (obj as? String)
        }
        
        if obj is NSNumber {
            return (obj as? NSNumber)?.toString()
        }
        return nil
    }
}


struct timeInter {
    var timer:DispatchSourceTimer!
    var count:Int?
    init(timer:DispatchSourceTimer,count:Int?) {
        self.timer = timer
        self.count = count
    }
}


/// GCD定时器倒计时⏳
///   - timeInterval: 循环间隔时间
///   - repeatCount: 重复次数
///   - handler: 循环事件, 闭包参数： 1. timer， 2. 剩余执行次数

@discardableResult
public func dispatchTimer(timeInterval: Double, repeatCount:Int, handler:@escaping (DispatchSourceTimer?, Int)->()) -> DispatchSourceTimer?{
    
    if repeatCount <= 0 {
        return nil
    }
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
    
    var count = repeatCount
    timer.schedule(wallDeadline: .now(), repeating: timeInterval)
    timer.setEventHandler(handler: {
        count -= 1
        DispatchQueue.main.async {
            handler(timer, count)
        }
        if count == 0 {
            timer.cancel()
        }
        
    })
    timer.resume()
    return timer
}

/// GCD定时器循环操作
///   - timeInterval: 循环间隔时间
///   - handler: 循环事件
public func dispatchTimer(timeInterval: Double, handler:@escaping (DispatchSourceTimer?)->()) {
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
    timer.schedule(deadline: .now(), repeating: timeInterval)
    timer.setEventHandler {
        DispatchQueue.main.async {
            handler(timer)
        }
    }
    timer.resume()
}

extension Dictionary where Key == String, Value == String  {
    func urlParams() -> String {
        let allkeys = self.keys
        var string = "?"
        for (index,key) in allkeys.enumerated() {
            let value = self[key]
            let valueString = "\(value ?? "")"
            let first = index > 0 ? "&":""
            let cstring = key+"="+valueString
            string.append(first+cstring)
        }
        return string
    }
}

extension Dictionary where Key == String, Value == Any {
    func jsonToData() -> Data? {
        if (!JSONSerialization.isValidJSONObject(self)) {
            print("is not a valid json object")
            return nil
        }
        //利用自带的json库转换成Data
        //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
        let data = try? JSONSerialization.data(withJSONObject: self, options: [])
        //Data转换成String打印输出
        let str = String(data:data!, encoding: String.Encoding.utf8)
        //输出json字符串
        print("Json Str:\(str!)")
        return data
    }
}

extension Data {
    func dataToDictionary() -> [String:Any]? {
        do{
            let json = try JSONSerialization.jsonObject(with: self, options: .mutableContainers)
            let dic = json as! Dictionary<String, Any>
            return dic
        }catch _ {
            print("失败")
            return nil
        }
    }
}


extension URL {
    func schemeToDic() -> [String:Any] {
        return self.absoluteString.schemeToDic()
    }
}


extension String {
    func schemeToDic() -> [String:Any] {
        if(self.contains("?")){
            var dict:Dictionary<String,Any> = [:]
            let datas = self.components(separatedBy: "?")
            if(datas.count > 1){
                let urlparams = datas[1].components(separatedBy: "&")
                for (_,keyvalue) in urlparams.enumerated(){
                    let temparr : [String] = keyvalue.components(separatedBy: "=")
                    let value = (temparr[1] == "") ? "":temparr[1]
                    let key   = temparr[0]
                    dict.updateValue(value.removingPercentEncoding!, forKey: key)
                }
                return dict
            }
        }
        return [:]
    }
}
